/**
 * Created by Dalyn on 2017/5/8.
 */
import React from "react";
import {hashHistory} from 'react-router';
import Relay from "react-relay";
import {_Input,_Button,_Icon,_Modal} from 'ANT_DE';
const Input = _Input,
    Button = _Button,
    Icon = _Icon, Modal = _Modal;
import {Upload,message,notification} from 'antd';


import SavePackStepMutation from '../mutation/SavePackStep';  //保存

import DelQiniuFileMutation from "../mutation/DelQiniuFileMutation" // 删除图片

import GetQiNiuToken from "../mutation/GetQiNiuTokenMutation"  //上传图片获取token

import GetPackStepInfo from '../mutation/GetPackStepInfoMutation'
import '../css/packStep.css';

// 细分组件
import {Header,PackList,ViewImgList,ViewAAddImg} from '../components/PackStep_Header';

import AddImgModal from "../components/AddImgModal";  //上传图片
import FileUpData from '../components/FileUpDataPro'  //上传附件


import {UpLoadCloudBatch} from '../components/FileImgOffLine';

import Config from "../../../../util/Config"

/*导出组件*/
export default class PackStep extends React.Component{

    constructor(props) {
        super(props);
        this.state = {
            imgCloudList:[],   //服务器获取文件列表
            imgLocalList:[],   //本地图片列表
            imgUploadList:[],  //需要批量上传的list

            previewImage: '',
            previewVisible:false,  //图片预览
            token:"",

            fileUpdataList:[],  //上传附件的list
            picRemoveList:[],   //删除图片的list

            saveLoading:false,  //保存loading

            isBatchUpload:false //是否批量上传文件
        };

        this.FixedImgSrc = Config.qiuniu;

        this.handlePreview = this.handlePreview.bind(this);
        this.handleCancel = this.handleCancel.bind(this);
        this.save = this.save.bind(this);

        this.handleChangeText = this.handleChangeText.bind(this);

        this.picRemove = this.picRemove.bind(this);
        this.beforeUpload = this.beforeUpload.bind(this);

        this.addImg = this.addImg.bind(this);

        this.addImg = this.addImg.bind(this);
        this.addFileImg = this.addFileImg.bind(this);

        this.addFileItem = this.addFileItem.bind(this); //上传文件 更新内部状态list
        this.fileBeforeload = this.fileBeforeload.bind(this);

        this.newProgress = this.newProgress.bind(this);  // 跟新进度条的事件

        this.removePic_C = this.removePic_C.bind(this);  // 更新删除的图片方法

        this.upLoadInfo_C = this.upLoadInfo_C.bind(this);     // 保存当前数据
    }


    componentWillMount(){
        // 获得
        this.pdId = this.props.pdId;

        // 获得上次保存的数据as
        // GetPackStepInfo
        Relay.Store.commitUpdate(new GetPackStepInfo({
            pdId:this.pdId
        }),{
                onSuccess:(res)=>{
                    console.log(res);
                    let data = res.getPackStepInfo.getPackStepInfo, 
                        A = [] ,
                        B = [];
                    if(data.errorCode == 0){
                        if(data.packStep){
                            A = JSON.parse(data.packStep.imgJson);
                            B = JSON.parse(data.packStep.fileJson);
                        }

                        this.setState({
                            imgCloudList:A,
                            fileUpdataList:B
                        })
                    }
                },
                onFailure:()=>{
                    message.error("拉取数据失败，请检查网络连接")
                }
        }
        );


        //获取上传图片所需的token
        Relay.Store.commitUpdate(
            new GetQiNiuToken({}), {
                onSuccess: (res) => {
                    let errorCode = res.getQiNiuToken.getQiNiuToken.errorCode;
                    if(errorCode==0){
                        let qiniutoken = res.getQiNiuToken.getQiNiuToken.qiniutoken;
                        this.setState({
                            token:qiniutoken
                        })
                    }
                }
            }
        );
    }

    componentDidMount(){
    }

    componentWillUnmount(){
    }

    //  验证格式需要通过obj传递到另一个组件调用，必须要在当前proto原型上，不可添加到自由属性.
    accept = ".jpg,.png,.gif,.jpeg,.bmp";
    fileAccept = ".pdf,.xlsx,.xls,.docx,.doc";

    /*文本输入change*/
    handleChangeText = (e,index)=>{
        this.state.stepArr[index].value = e.target.value;
        this.setState({
            stepArr:this.state.stepArr
        });
    };

    // 删除图片
    picRemove(index,type){
        //过渡动画
        const t = type === "cloud" ? "imgCloudList" : "imgLocalList",
                updata = ()=>{
                    this.setState({
                        imgCloudList:this.state.imgCloudList,
                        imgLocalList:this.state.imgLocalList
                    })
                };

        this.state[t][index].file.__transClass = "leave";
        updata();

        // 判断是否为本地图片或者是cloud图片 记录删除的key;
        setTimeout(()=>{
            this.state[t].splice(index,1);
            updata();
        },300);

        if(type === "cloud"){
            //下列固定为0，因为list最多只能上传一个，固0
            const Rn =  this.state.imgCloudList[index].file.response.key;
            this.state.picRemoveList.push(Rn);
        }
    }


    // 更新进度条方法
    newProgress(per,i){
        this.state.imgLocalList[i].progress = per;
        this.setState({
            imgLocalList:this.state.imgLocalList
        })
    }


    // 删除图片的提交
    removePic_C(){
        let R = this.state.picRemoveList;

        if(R.length === 0 ){ return; }

        // 删除图片;
        Relay.Store.commitUpdate(
            new DelQiniuFileMutation({
                fileKey:R.join(",")
            }),
            {
                onFailure: () => {
                    message.error("")
                },
                onSuccess: (response) => {
                    let errorCode = response.delQiniuFile.delQiniuFile.errorCode;
                    if (errorCode == 0) {
                        this.setState({picRemoveList:[]});
                    }else if(errorCode == 500){
                        message.error("服务器错误，请联系管理员")
                    }
                }
            }
        )
    }

    //发送信息给后台方法
    upLoadInfo_C(imgJson,fileJson,isNoti){
        if( !imgJson && !fileJson ){ return; }

        this.setState({saveLoading:true});

        Relay.Store.commitUpdate(
            new SavePackStepMutation({
                pdId:this.pdId,
                imgJson:imgJson,
                fileJson:fileJson,
            }), {
                onFailure: (err) => {
                    message.error("网络请求失败");
                },
                onSuccess: (res)=> {
                    const L = res.savePackStep.savePackStep;

                    if( L.errorCode == 0 ){
                        if(isNoti){
                            notification.open({
                                message: `上传${L.value}`,
                                description: '上传图片成功，下次进入将为您展示.',
                                placement:"bottomLeft",
                                icon: <Icon type="smile-circle" style={{fontSize:30, color: '#108ee9' }} />
                            });

                            // 上传完成清空本地图片列表
                            this.setState({
                                imgCloudList:this.state.imgCloudList.concat(this.state.imgLocalList),
                                imgLocalList:[]
                            })
                        }else{
                            message.success("保存成功");
                        }
                    }else if( L.errorCode == 500 ){
                        message.error(" 服务器错误，请联系系统管理员 ")
                    }
                }
            }
        );
        this.setState({saveLoading:false});
    };

    save(){

        // 检查是否有改动，否则不保存
        if(this.state.picRemoveList.length <= 0 && this.state.imgLocalList.length <=0 ){
            message.info("没有什么可保存的哟！");
            return;
        }

        //  cloudList 与 localList 合并
        const imgList = this.state.imgCloudList.concat(this.state.imgLocalList);

        // 有需要上传的图片时
        if(this.state.imgLocalList.length > 0){
            // 整理纯file格式发送
            let list = this.state.imgLocalList;

           const arr = list.map((item,index)=>item.file);

            // console.log(this.state.imgUploadList);
            this.setState({
                imgUploadList:arr,
                isBatchUpload:true
            });

        }else{
            // 不上传本地文件时，
            // 更新
            this.upLoadInfo_C(JSON.stringify(imgList),JSON.stringify(this.state.fileList),false);
        }

        // 删除图片
        this.removePic_C()
    }

    // 预览图片关闭
    handleCancel = ()=>{
        this.setState({
            previewVisible:false,
        });
        // 优化用户体验，延时一秒清空图片
        setTimeout(()=>{
            this.setState({
                previewImage:""
            })
        },700);
    };


    // 上传之前进行验证
    beforeUpload(files){
        const MaxSize = 8;  //最大限度 8M;
        const file = files[0];

        // 图片格式
        if(file.type !== "image/jpeg" && file.type !== "image/jpg" && file.type !== "image/png" && file.type !== "image/gif" && file.type !== "image/bmp"){
            message.error("图片格式错误");
            return false;
        }

        // 图片大小
        if( file.size / 1024 / 1024 > MaxSize ){
            message.error("图片大小超过限制");
            return false;
        }
    }

    // 预览图片
    handlePreview = (index,type) => {
        // 两种预览方式 ， 一种是线上 一种是本地
        const t = type === "cloud" ? "imgCloudList" : "imgLocalList";
        this.setState({
            previewVisible:true,
            previewImage:this.state[t][index].file.src
        })
    };

    // 添加图片
    addImg(){
        const l = this.state.imgLocalList.length + this.state.imgCloudList.length;
        if(l < 20){
            this.refs.addFileImgModal.setState({
                visible:true
            })
        }else{
            message.error("图片最多上传20张，您已超过上限")
        }
    }

    //上传图片配置
    uploadPlugin = {
        action: 'http://up-z2.qiniu.com',
        accept:this.accept,
        beforeUpload:this.fileBeforeload,
    };

    // 上传文件配置
    fileUploadPlugin = {
        action: 'http://up-z2.qiniu.com',
        beforeUpload:this.fileBeforeload,
        accept:this.fileAccept,
    };


    // 新增图片函数  (push 到当前组件)
    addFileImg({file,text,base64}){
        if (file) {
            let img = this.state.imgLocalList;
            file.src = base64;
            img.push({file,text});
            this.setState({
                    imgLocalList: this.state.imgLocalList
                })
            }
        else{
            message.error("最多只可上传20张");
        }
    }


    //附件上传之前验证
    fileBeforeload(files){
        const MaxSize = 10;  //最大限度 10M;

        if( files[0].size / 1024 / 1024 > MaxSize ){
            message.error("文件大小超过限制");
            return false;
        }

    }

    // 新增文件函数，（push 当前组件）
    addFileItem(fileList){
        this.state.fileUpdataList = fileList;
        this.setState({
            fileUpdataList:this.state.fileUpdataList
        })
    }


    imgUploadChange(o){
        if(o.status === "done"){

        }
    }


    render(){
        const {
                saveLoading,
                previewVisible,
                previewImage,
                imgLocalList,
                imgCloudList,
                token,
                fileUpdataList,
                isBatchUpload,
                imgUploadList
        } = this.state,
            {} = this.props;

        return (
            <div className="poduction_manage_tab_box" >
                <div className="product_packagSteps">

                    {/*附件 列表*/}
                    <FileUpData
                        className="packagSteps_updataFile"
                        filePlugin={this.fileUploadPlugin}
                        fileList={fileUpdataList}
                         //回调，第一个参数为file,第二个参数为本地name
                        token={token}
                        isFile={fileUpdataList < 10} //是否显示上传附件按钮
                    />

                    <div className="product_packagSteps-upload">
                        {/*图片[cloud]展示系列表*/}
                        {
                           imgCloudList.length !== 0 && imgCloudList.map((item,index)=>
                                <ViewImgList
                                    key={item.file.uid}
                                    imgSrc={item.file.src}
                                    imgName={item.file.name}
                                    handlePreview={(e)=>this.handlePreview(index,"cloud",e)}
                                    handleRemove={(e)=>this.picRemove(index,"cloud",e)}
                                    textValue={item.text}
                                    transClass={item.file.__transClass}   //过渡动画类，中途插入
                                />
                            )
                        }

                        {/*图片[local]展示系列表*/}
                        {
                           imgLocalList.length !==0 && imgLocalList.map((item,index)=>
                                <ViewImgList
                                    key={item.file.uid}
                                    imgSrc={item.file.src}
                                    imgName={item.file.name}
                                    handlePreview={(e)=>this.handlePreview(index,"local",e)}
                                    handleRemove={(e)=>this.picRemove(index,"local",e)}
                                    textValue={item.text}
                                    progress = {item.progress}
                                    transClass={item.file.__transClass}   //过渡动画类，中途插入
                                />
                            )
                        }

                        {/*批量上传文件*/}
                        <UpLoadCloudBatch
                            onChange={this.imgUploadChange}
                            isUpdata={isBatchUpload}
                            fileList={imgUploadList}
                            {...this.uploadPlugin}
                            data={{
                                token:this.state.token,
                                key:new Date().getTime()
                            }}
                        />

                        {/*添加图片模版*/}
                        {
                            imgCloudList.length + imgLocalList.length <20 &&
                            <ViewAAddImg  onClick={this.addImg} />
                        }

                        {/*预览图片*/}
                        <Modal visible={previewVisible} footer={null} width={500} onCancel={this.handleCancel}>
                            <img alt="example" style={{ width: '100%' }} src={previewImage} />
                        </Modal>

                        {/*添加图片弹出框*/}
                        <AddImgModal
                            uploadPlugin = {this.uploadPlugin}   //上传参数配置
                            ref="addFileImgModal"   //ref方便visible显示
                            token={token}   // 上传图片时，必须的token，(此token异步返回)
                            addFileImg={this.addFileImg}   //上传成功的回调，第一个参数的第一个属性为返回的fill,第二个属性为text描述
                            fileBeforeload={this.fileBeforeload}
                            //  text 描述 props配置信息
                            TextProps={{
                                className:"packagSteps_AddImgModal_textArea",
                                rows:3,
                                placeholder:"请输入描述信息"
                             }}
                            limit={{width:800,height:800}} //最小宽高限制参数
                        />
                    </div>

                    <div className="packagSteps_footer">
                        <Button type="primary" loading={saveLoading} onClick={this.save} disabled={saveLoading}> 保存 </Button>

                    </div>
                </div>
            </div>
        )
    }
}